import { Injectable } from '@angular/core';
import { CoreModule } from '../core.module';
import { StorageService } from '../sotrage/storage.service';

// tslint:disable-next-line:interface-over-type-literal
export type Token = { loginId: string; token: string, exp: number };

@Injectable({
  providedIn: CoreModule
})
export class TokenService {

  private readonly defaultExpTtl = 15 * 60 * 1000;
  private readonly tokenKey = 'wenyao-web-fallet-token';

  private token: Token;

  public saveToken(loginId: string, token: string, exp?: number) {
    if (!exp) {
      exp = new Date().getTime() + this.defaultExpTtl;
    }
    this.token = {
      loginId: loginId,
      token: token,
      exp: exp
    };
    this.storageService.set(this.tokenKey, this.token);
  }

  public getToken() {
    if (!this.token) {
      this.token = this.storageService.get<Token>(this.tokenKey);
    }
    return this.token;
  };

  

  public removeToken() {
    this.storageService.remove(this.tokenKey);
  }

  constructor(
    private storageService: StorageService
  ) {

  }
}
